﻿
/*
*      
*          ┌─┐       ┌─┐
*       ┌──┘ ┴───────┘ ┴──┐
*       │                 │
*       │       ───       │
*       │  ─┬┘       └┬─  │
*       │                 │
*       │       ─┴─       │
*       │                 │
*       └───┐         ┌───┘
*           │         │
*           │         │
*           │         │
*           │         └──────────────┐
*           │                        │
*           │                        ├─┐
*           │                        ┌─┘    
*           │                        │
*           └─┐  ┐  ┌───────┬──┐  ┌──┘         
*             │ ─┤ ─┤       │ ─┤ ─┤         
*             └──┴──┘       └──┴──┘ 
*                 神兽保佑 
*                 代码无BUG! 
*  Author shang
*  2022-07-21 15:47:40
*/

using System.Collections.Concurrent;

namespace TS.Memory;

public class SafeDicMemCache<TKey, TValue>
{
    private ConcurrentDictionary<TKey, TValue> _dic = new();
    public string NamePrefix { get; private set; }
    
    public SafeDicMemCache(string namePrefix)
    {
        NamePrefix = namePrefix;
    }
    
    public TValue Get(TKey key)
    {
        if (_dic.TryGetValue(key, out TValue loc))
        {
            return loc;
        }
        return default;
    }

    public void Clear()
    {
        _dic.Clear();
    }
    public bool IsExits(TKey key)
    {
        if(key == null)
        {
            return false;
        }
        if (_dic.TryGetValue(key, out TValue loc))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 设置的值为null时，会将该key移除
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool Set(TKey key, TValue val)
    {
        if (val == null)
        {
            return _dic.TryRemove(key, out TValue _loc);
        }
        TValue loc = _dic.AddOrUpdate(key, val, (k, n) => {
            return val;
        });
        return loc != null;
    }
    
    public void Init<T>(IList<T> datas, Func<T, KeyValuePair<TKey, TValue>> func)
    {
        _dic.Clear();
        foreach (var item in datas)
        {
            if (item == null) continue;
            var kv = func(item);
            _dic.TryAdd(kv.Key, kv.Value);
        }
    }

    public IDictionary<TKey, TValue> AsDic()
    {
        return _dic;
    }
}
